package com.sanbi.common.util;

import com.sanbi.common.dto.UserDto;
import com.sanbi.common.vo.UserVo;

import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

@Component
public class BeanUtil implements ApplicationContextAware {
    protected static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public static <T> T getBean(Class<T> c) {
        return context.getBean(c);
    }

    @SneakyThrows
    public static <T, V> void copyBean(T sourceBean, V targetBean) {
        BeanUtils.copyProperties(targetBean, sourceBean);
    }

    @SneakyThrows
    public static <T, V> List<V> convertListBeans(T sourceBean) {
        List<V> outVos=new ArrayList<>();
        org.springframework.beans.BeanUtils.copyProperties(sourceBean, outVos);

        return outVos;
    }

    @SneakyThrows
    public static <S, T> List<T> convertList(List<S> sources, Supplier<T> target) {
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            copyBean(source, t);
            list.add(t);
        }
        return list;
    }

    @SneakyThrows
    public static <T, V> V convertBean(T sourceBean, Class<V> targetClass) {
        V targetBean=targetClass.newInstance();
        copyBean(sourceBean, targetBean);

        return targetBean;
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        List<UserDto> userDtos=new ArrayList<>();
        UserDto userDto1=new UserDto();
        userDto1.setAge(11);
        userDto1.setId(1);
        userDto1.setName("name111");
        userDto1.setEmail("name111@mail.com");
        userDtos.add(userDto1);

        UserDto userDto2=new UserDto();
        userDto2.setAge(22);
        userDto2.setId(2);
        userDto2.setName("name222");
        userDto2.setEmail("name222@mail.com");
        userDtos.add(userDto2);

//        List<UserVo> userVos=BeanUtil.convertListBeans(userDtos);
//        SingletonSupplier<UserVo> target=new SingletonSupplier<UserVo>();
        List<UserVo> userVos=convertList(userDtos,UserVo::new);
        System.out.println(userVos);

        UserVo userVo=convertBean(userDto1,UserVo.class);

        System.out.println(userVo);


    }

}
